package cn.pet.service.manage.utils;

import cn.pet.service.manage.entity.PetGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;

@Slf4j
public class FileUtil {

    /**
     * 上传文件
     *
     * @return
     */
    public static Boolean uploadFile(MultipartFile file, String parentPath, PetGoods petGoods) {
        if (!file.isEmpty()) {
            //获取原文件名
            String originalFilename = file.getOriginalFilename();
            //主路径
            String twoPath = DateUtils.dateTimeNow();
            String fileParenPath = parentPath  + "/" +twoPath;
            if (originalFilename == null || "".equals(originalFilename)){
                originalFilename = DateUtils.dateTimeNow();
            }
            petGoods.setPicture("/"+twoPath+"/"+originalFilename);
            File localFile = new File(fileParenPath, originalFilename);
            File fileParent = new File(fileParenPath);
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            try {
                file.transferTo(localFile);
            } catch (IOException e) {
                e.printStackTrace();
                log.debug("文件上传失败...");
                return false;
            }
        } else {
            log.debug("文件为空...");
        }
        return true;
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    public static boolean removeFile(String filePath){
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }


    /**
     * 删除文件夹下所以文件列表及文件夹
     * @param file
     * @return
     */
    public static Boolean deleteFile(File file) {
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            if (log.isDebugEnabled()){
                log.debug("文件夹不存在");
            }
            return false;
        }
        //获取目录下子文件
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                //递归删除目录下的文件
                deleteFile(f);
            } else {
                //文件删除
                f.delete();
                //打印文件名
                if (log.isDebugEnabled()){
                    log.debug("文件名{}",f.getName());
                }
            }
        }
        //文件夹删除
        file.delete();
        return true;
    }


    /**
     * 文件转二进制
     * @param filePath
     * @return
     */
    public static byte[] fileToBytes(String filePath){
        File file = new File(filePath);
        if (!file.exists())return new byte[0];
        try(InputStream inputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ) {
            byte[] buf = new byte[1024];
            int len;
            if ((len=bufferedInputStream.read(buf))>=0){
                outputStream.write(buf,0,len);
            }
            return outputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将二进制流转换为文件
     * @param bytes
     * @return
     */
    public static String bytesToFile(byte[] bytes,String fileName){
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (FileOutputStream outputStream = new FileOutputStream(fileName);){
            outputStream.write(bytes);
            return fileName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将二进制流转换为文件
     * @param bytes
     * @param fileName
     */
    public static void bytesToFileSpring(byte[] bytes,String fileName){
        try {
            FileCopyUtils.copy(bytes,new File(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将文件转base64
     * @param filePath 文件路径
     */
    public static String fileToBase64(String filePath){
        try( InputStream fileInputStream = new FileInputStream(new File(filePath));
             BufferedInputStream buf = new BufferedInputStream(fileInputStream);
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();){
            int len;
            byte [] bytes = new byte[1024];
            while ((len=buf.read(bytes))!=-1){
                byteArrayOutputStream.write(bytes,0,len);
            }
            return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 将base64字符串转文件
     * @param base64Str base64字符串
     */
    public static void base64ToFile(String base64Str,String fileName){
        //解码
        byte [] bytes = Base64.getDecoder().decode(base64Str);
        try (FileOutputStream outputStream = new FileOutputStream(fileName);){
            outputStream.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
//        Boolean aBoolean = deleteFile(new File("D:\\data\\2022-07-18"));
//        System.out.println(DateUtils.dateTimeNow());
//        System.out.println(aBoolean);
//        System.out.println(fileToBytes("D:\\inspection\\file\\idCardFile\\检定员-A-3-1-1_null_20220811170107\\Inked微信截图_20220319115738_LI.jpg"));

//        System.out.println(fileToBase64("D:\\inspection\\file\\idCardFile\\检定员-A-3-1-1_null_20220811170107\\Inked微信截图_20220319115738_LI.jpg"));

        String basePath = "G://base/path";
        String allPath = "G://base/path/type/test.txt";
        System.out.println(allPath.substring(basePath.length()));
    }

}
